/**
 * 
 */
package io.potato.core.util.xml;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.apache.commons.lang3.StringUtils;

/**
 * Jaxb LocalDateTime 日期转换
 * @author timl
 * created: 2019年1月15日 下午5:58:00
 */
public class DateTimeAdapter  extends XmlAdapter<String, LocalDateTime> {
	
	private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
	
	private static final DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	@Override
	public LocalDateTime unmarshal(String v) throws Exception {
		if (StringUtils.isEmpty(v)) {
			return null;
		}
		
		try {
			v = v.trim();
			if (v.length() == 14) {
				return LocalDateTime.parse(v, dtf);
			}
			
			v = v.replace('/', '-');
			return LocalDateTime.parse(v, dtf2);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public String marshal(LocalDateTime v) throws Exception {
		return dtf.format(v);
	}

}
